<template>
	<view class="pageview">
		<cl-navbar autoBack placeholder :title="$t('redPacket.send.sent')"></cl-navbar>
		<view class="cententView">
			<view class="inputAllView">
				<u-input placeholder="0.00" inputAlign="right" border="none" type="digit" v-model="money"
					@input="handleInput">
					<view style="display: flex;align-items: center;" slot="prefix">
						<text style="font-size: 28rpx;color: #595A66;">{{$t("redPacket.send.singleAmount")}}</text>
					</view>
					<view slot="suffix">
						<text style="font-size: 32rpx;color: #5B5B5B;">{{$t("redPacket.display.yuan")}}</text>
					</view>
				</u-input>
			</view>
			<view class="inputAllView">
				<u-input :placeholder="$t('chat.msg.redPacket.defaultMessage')" v-model="remark" border="none"></u-input>
			</view>
			<view class="moneyall">
				<text style="font-size: 60rpx;">￥</text>
				{{allMoney}}
			</view>
			<view class="sendBtn" @click="sendPsw">{{$t("redPacket.send.sendButton")}}</view>
		</view>
		<jp-pwd ref="jpPwds" @completed="completed" :money="pwd.money"
			:tite="pwd.tite" :cancelType="pwd.cancelType" contentsColor="#555" :isPwy="pwd.isPwy"
			titeColor="#333">
			<view slot="custom" class="yueview">
				<text class="fukuanfangshi">{{$t("redPacket.send.paymentMethod")}}</text>
				<text class="yuetext">{{$t("redPacket.send.accountBalance",{balance:balance ? (balance*100/100).toFixed(2) : '0.00'})}}</text>
			</view>
		</jp-pwd>
		<view>
			<cl-model ref="clmodel"></cl-model>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		v4 as uuidv4
	} from 'uuid';
	import messageApi from '@/services/api/msg.js'
	export default {
		data() {
			return {
				money: '',
				remark: '',
				chatInfo: null,
				balance:0,
				pwd: {
					money: '', //支付金额
					tite: this.$t("redPacket.send.pwdtitle"), //标题
					cancelType: false, //是否输入完密码后消失
					isPwy: true
				},
				isPay:false,//正在支付中
			};
		},
		computed: {
			...mapState({
				user_info: state => state.user.user_info,
			}),
			allMoney() {
				let smoney = Number(this.money) || 0
				return smoney.toFixed(2)
			},
		},
		onLoad() {
			let query = this.$Route.query
			if (query.info) {
				this.chatInfo = query.info
			}
		},
		methods: {
			// 处理输入事件，限制两位小数
			handleInput(value) {
				console.log(value);
				// 使用正则表达式限制两位小数
				const regex = /^(0|[1-9]\d*)(\.\d{0,2})?$/;
				if (regex.test(value)) {
					this.money = value;
				} else {
					// 如果输入非法，则处理
					if (value.indexOf('.') !== -1) {
						// 存在小数点，截取到小数点后两位
						const decimalIndex = value.indexOf('.');
						this.$nextTick(() => {
							this.money = value.slice(0, decimalIndex + 3);
						})

					} else {
						// 不存在小数点，截取整数部分
						this.$nextTick(() => {
							this.money = value.replace(/[^0-9]/g, ''); // 只保留数字
						})

					}
				}
			},
			// 校验输入值的最小值
			validateAmount() {
				if (this.money && parseFloat(this.money) < 0.01) {
					this.money = '0.01'; // 最小值为 0.01
				}
			},
			completed(e) {
				this.sendRed(e)
				this.$refs.jpPwds.toCancel()
				// if (e == '123456') {
				// 	this.$refs.jpPwds.toCancel()
				// } else {
				// 	this.pwd.msg = '密码错误'
				// 	this.$refs.jpPwds.backs()
				// }
			},
			sendPsw() {
				if(!this.money || this.money < 0.01){
					uni.showToast({
						title:this.$t("redPacket.send.validation.moneyEmpty"),
						icon:'none'
					})
					return
				}
				if(this.isPay)return
				this.isPay = true
				uni.showLoading({
					title: this.$t("api.loading.pay.send")
				})
				uni.$api.user.getBalance().then(res=>{
					if(res && res.code == 200){
						this.balance = res.data.virtual_conis_balance
						this.pwd.money = '￥'+ this.allMoney
						if(res.data.is_set_pay_password){
							this.$refs.jpPwds.toOpen()
						}else{
							this.$refs.clmodel.show({
								title: this.$t("common.Tips"),
								confirmText:this.$t("redPacket.send.dialog.setPayPwd"),
								content: this.$t("redPacket.send.dialog.noPayPwd"),
								confirm: (e) => {
									e.showModel = false
									this.$Router.push({
										name: 'payPassword'
									});
								}
							})
						}
					}
					uni.hideLoading()
					this.isPay = false
				}).catch(e=>{
					uni.hideLoading()
					this.isPay = false
				})
			},
			async sendRed(pay_password) {
				uni.showLoading({
					title: this.$t("api.loading.msg.send")
				})
				try {
					let res = await uni.$api.chat.redPacketSend({
						chat_type: '0',
						packet_type: '0',
						amount: this.money, //红包总金额
						remark: this.remark || this.$t("chat.msg.redPacket.defaultMessage"),
						amount_type: '0', //使用的余额类型
						quantity: '1', //红包数量必须大于等于1
						target_id: this.chatInfo.uuid, //目标id
						pay_password,
					})
					if (res && res.code == 200) {
						this.sendMsg(res.data)
					} else {
						uni.hideLoading()
					}
				} catch (e) {
					uni.hideLoading()
				}
			},
			async sendMsg(data) {
				console.log(data);
				try {
					let wy_id = uuidv4();
					let resmsg = await messageApi.directsend({
						target_id: this.chatInfo.uuid,
						local_id: wy_id,
						msg_type: 'r_p',
						content_text: [{
							r_p: {
								red_packet_id: data.id, //红包id
								amount: data.amount, //红包总金额
								remark: this.remark || this.$t("chat.msg.redPacket.defaultMessage"),
								chat_type: data.chat_type, //红包(0:私聊;1群聊)
								amount_type: data.amount_type, //0普通红包;1手气红包
								target_id: data.target_id,
								sender_id: data.sender_id,
								quantity: data.quantity, //红包总数量
								per_user_limit: data.per_user_limit, //每人可抢次数
								expiration_time: data.expiration_time, //红包过期时间
							}
						}]
					}, this.chatInfo.chat_type);
					if (resmsg) {
						uni.showToast({
							title: this.$t("tost.msg.beenSent"),
							icon: 'none',
						})
						setTimeout(() => {
							this.$Router.back()
						}, 1000)
					}
				} catch (e) {
					console.log(e);
				}
				uni.hideLoading()
			}
		}
	}
</script>

<style lang="scss">
	.cententView {
		margin: 0 30rpx;
		display: flex;
		flex-direction: column;
	}

	.selectView {
		display: flex;
		align-items: center;
		font-size: 26rpx;
		color: #FC8F2C;
	}

	.peopleCount {
		font-size: 24rpx;
		color: #5B5B5B;
		margin-top: 30rpx;
	}

	.inputAllView {
		margin-top: 30rpx;
		background-color: #e4e4e8;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 20rpx;
		border-radius: 10rpx;
	}

	.moneyall {
		margin-top: 100rpx;
		text-align: center;
		font-size: 80rpx;
		color: #000000;
		letter-spacing: 0;
		font-weight: 700;
	}

	.sendBtn {
		align-self: center;
		margin-top: 100rpx;
		padding: 20rpx 80rpx;
		background-image: linear-gradient(270deg, #FF7B3C 0%, #FF5B7C 100%);
		border-radius: 20rpx;
		font-size: 30rpx;
		color: #FFFFFF;
	}
	.yueview{
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		.fukuanfangshi{
			font-size: 26rpx;
			color: #d4a150;
		}
		.yuetext{
			font-size: 26rpx;
			color: #d4a150;
		}
	}
</style>